
var date=echartUtil.GetDateStr(0);
var startDay=echartUtil.GetDateStr(-30);
var deptName="";
var searchingWhere="";
var deptId="";

//相关业务逻辑
$(function(){
	page.setTime();
	echart.getClock();
//	echart.getClockResult();
	page.bind();
	nameToIdUtil.getProductionDepartment("productionDepartment");
	echartUtil.getManager(deptName);
	page.getTableData(deptName,date,startDay,searchingWhere,deptId);
	page.getEchart(deptName,date,startDay,searchingWhere,deptId);
//	page.getReachParam();
});

var table;
var page={//页面总变量
		bind:function(){
			$("#downlodeExcle").bind("click",function(){
				var url="workshop/downlodeReachFile?workShop="+deptName+"&date="+date+"&startDay="+startDay+"&searchingWhere="+searchingWhere;
				tableUtil.download(url);
			});
			
			$("#isHidden").bind("click",function(){
				var text=$(this).text();
				if(text=="隐藏"){
					$(".middle").hide();
					$(this).text("显示");
				}else{
					$(".middle").show();
					$(this).text("隐藏");
				}
			});
			
			//点击部门
			$("#totalTable").bind("change",function(){
				deptName=$(this).val();
				page.getTableData(deptName,date,startDay,searchingWhere,deptId);
				page.getEchart(deptName,date,startDay,searchingWhere,deptId);
				echartUtil.getManager(deptName);
			});
			
			//点击搜索
			$("#searchingWhereBtn").bind("click",function(){
				searchingWhere=$("#searchingWhere").val();
				page.getTableData(deptName,date,startDay,searchingWhere,deptId);
				page.getEchart(deptName,date,startDay,searchingWhere,deptId);
			});
			
			//查看汇总
			$("#seeSumBtn").bind("click",function(){
				$("#sumModal").modal("show");
			});
			
			/**
			 *  查看人员汇总
			 */
			$("#peopleSumBtn").bind("click",function(){
				$("#peopleSumModal").modal("show");
			});
			
			
			$("#productionDepartment").bind("change",function(){
				deptId=$("#productionDepartment").val();
				page.getTotal(deptId);
				page.getTableData(deptName,date,startDay,searchingWhere,deptId);
				page.getEchart(deptName,date,startDay,searchingWhere,deptId);
			});
		},
		//获取所有车间达成率
		getTotal:function(deptId){
			nameToIdUtil.getWorkShopNameAndId("totalTable",deptId);
		},
		//获取表格数据
		getTableData:function(workShop,date,startDay,searchingWhere,deptId){
			table=ajaxUtil.dataTablesAjaxNotFxiaction("dataTable",10,"workshop/getTableData",
					{'workShop':workShop,'date':date,'startDay':startDay,'searchingWhere':searchingWhere,'deptId':deptId},[
					{"data":"name"},
					{"data":"companyOrderId"},
					{"data":"factoryId"},
					{"data":"coustomId"},
					{"data":"procedur"},
					{"data":"capacity"},
					{"data":"oneTime",render: function (data) {
						return data.toFixed(2);
			        }},
					{"data":"effectiveTime",render: function (data) {
						return data.toFixed(2);
			        }},
					{"data":"workEffective",render: function (data) {
						data=data.toFixed(2);
						var html=data+"%";
						if(data>120){
							html+="<span style='color:red'>单付时间过大</span>"
						}
			            return html;
			          }},
					{"data":"workDate"},
					{"data":"price"},
					{"data":"sumPrice"}
			]);
		},
		getEchart:function(workShop,date,startDay,searchingWhere,deptId){
			ajaxUtil.ajaxRuquest('workshop/getPersonData',{ 'workShop':workShop,'date':date,'startDay':startDay,'searchingWhere':searchingWhere,'deptId':deptId},function(data){
				   var dayCount=datedifference(startDay,date);
				   dayCount= dayCount+1;
				   var html="";
				   var pruData=data.haveProcedure;
				   var data=data.noProcedure;
				   var chartData=new Object();//渲染图表的数据
				   var chartName=new Array();//名字
				   var chartCapacity=new Array();//产能
				   var sumPrice=new Array();//单付时间
				   var chartEffectiveTime=new Array();//有效时间
				   var chartWorkEffective=new Array();//工作效率
				   for(var key in data){
					   chartName.push(data[key].name);
					   chartCapacity.push(data[key].capacity.toFixed(2));
					   sumPrice.push(data[key].sumPrice.toFixed(2));
					   chartEffectiveTime.push(data[key].effectiveTime.toFixed(2));
					   chartWorkEffective.push((data[key].workEffective/dayCount).toFixed(2));
				   }
				   
				   chartData.chartName=chartName;
				   chartData.chartCapacity=chartCapacity;
				   chartData.sumPrice=sumPrice;
				   chartData.chartWorkEffective=chartWorkEffective;
				   chartData.chartEffectiveTime=chartEffectiveTime;
				   echart.echarts(chartData);
				   for(var key in pruData){
					   html+="<tr>" +
				   		"<td>"+pruData[key].name+"</td>" +
				   		"<td>"+pruData[key].procedur+"</td>" +
				   		"<td>"+pruData[key].capacity.toFixed(2)+"</td>" +
				   		"<td>"+pruData[key].sumPrice.toFixed(2)+"</td>" +
				   		"<td>"+dayCount+"</td>" +
				   		"<td>"+pruData[key].effectiveTime.toFixed(2)+"</td>" +
				   		"<td>"+(pruData[key].workEffective/dayCount).toFixed(2)+"%</td>" +
				   		"</tr>";
				   }
				   var propleHtml="";
				   for(var key in data){
					   propleHtml+="<tr>" +
					   "<td>"+data[key].name+"</td>" +
					   "<td>"+data[key].capacity.toFixed(2)+"</td>" +
					   "<td>"+data[key].sumPrice.toFixed(2)+"</td>" +
					   "<td>"+dayCount+"</td>" +
					   "<td>"+data[key].effectiveTime.toFixed(2)+"</td>" +
					   "<td>"+(data[key].workEffective/dayCount).toFixed(2)+"%</td>" +
					   "</tr>";
				   }
				   $("#sumModalTBody").html(html);
				   $("#peopleSumModalTBody").html(propleHtml);
				  
			});
		},
		//设置本人页面参数（本页面查看部门部门）
		setReachParam:function(workShop){
			ajaxUtil.ajaxRuquest('pageParam/setReachParam',{'reachParam':workShop},function(data){
				console.log("员工达成率看板设置车间失败");
			});
		},
		//获取页面参数
//		getReachParam:function(){
//			$.ajax({
//				url:'pageParam/getReachParam',
//				success:function(data){
//					if(data.result){
//						if(deptName!=data.data.reachParam){
//							deptName=data.data.reachParam;
//							console.log(deptName);//
//							page.getTableData(deptName);
//						}
//					}else{
//						console.log("获取员工达成率看板车间失败");
//					}
//				}
//			});
//		},
       //设置时间
		setTime:function(){
			$("#startDay").val(startDay);
			$("#yestarday").val(date);
		}
}


function datedifference(sDate1, sDate2) {    //sDate1和sDate2是2006-12-18格式  
    var dateSpan,
        tempDate,
        iDays;
    sDate1 = Date.parse(sDate1);
    sDate2 = Date.parse(sDate2);
    dateSpan = sDate2 - sDate1;
    dateSpan = Math.abs(dateSpan);
    iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
    return iDays
};

var echart={
		echarts:function(chartData){
			//基于准备好的dom，初始化echarts实例
			var myChart = echarts.init(document.getElementById('chartDiv'));
			    myChart.setOption({
			        title: {
			            text: ''
			        },
			        toolbox: {
			            show: true,
			            orient: 'vertical',
			            left: 'right',
			            top: 'center',
			            feature: {
			                mark: {show: true},
			                dataView: {show: true, readOnly: false},
			                magicType: {show: true, type: ['line', 'bar', 'stack', 'tiled']},
			                restore: {show: true},
			                saveAsImage: {show: true}
			            }
			        },
			        tooltip: {},
			        legend: {
			            data:['作业产能','有效时间', '工作效率','总价']
			        },
			        xAxis: {
			            data: chartData.chartName
			        },
			        yAxis:  [
			        	{  
			                type : 'value' 
			            }  
			        ],
			        series:  [{
			            name: '作业产能',
			            type: 'line',
			            data: chartData.chartCapacity,
			            itemStyle: {
		                    normal: {
		                        label: {
		                            show: true,
		                            positiong: 'top',
		                            formatter: '{c}'
		                        }
		                    }
		                }
			        },{
			            name: '有效时间',
			            type: 'line',
			            data: chartData.chartEffectiveTime,
			            itemStyle: {
		                    normal: {
		                        label: {
		                            show: true,
		                            positiong: 'top',
		                            formatter: '{c} h'
		                        }
		                    }
		                }
			        },{
			            name: '工作效率',
			            type: 'line',
			            data: chartData.chartWorkEffective,
			            itemStyle: {
		                    normal: {
		                        label: {
		                            show: true,
		                            positiong: 'top',
		                            formatter: '{c} %'
		                        }
		                    }
		                }
			        },{
			            name: '总价',
			            type: 'line',
			            data: chartData.sumPrice,
			            itemStyle: {
		                    normal: {
		                        label: {
		                            show: true,
		                            positiong: 'top',
		                            formatter: '{c} ￥'
		                        }
		                    }
		                }
			        }]
			    });
		},
		getClock:function(){
			$.ajax({
				url:'weiXin/getClock',
				success:function(data){
					if(data.result){
						data=data.data;
						var myChart = echarts.init(document.getElementById('clockChartDiv'));
						 myChart.setOption({
							 title: {
						            text: '上下班打卡统计',
						            x:'center',
						            y: 'top'
						        },
							 tooltip: {
							        trigger: 'item',
							        formatter: "{a} <br/>{b}: {c} ({d}%)"
							    },
							    legend: {
							    	orient: 'horizontal',
							        x: 'center',
							        y: 'bottom',
							        data:['正常人数'+data.successUserCount,'异常人数'+data.errorUserCount],
							    },
							    series: [
							        {
							            name:'上班打卡',
							            type:'pie',
							            radius: ['50%', '60%'],
							            avoidLabelOverlap: false,
							            label: {
							                normal: {
							                    show: false,
							                    position: 'center'
							                },
							                emphasis: {
							                    show: true,
							                    textStyle: {
							                        fontSize: '20',
							                        fontWeight: 'bold'
							                    }
							                }
							            },
							            labelLine: {
							                normal: {
							                    show: true
							                }
							            },
							            data:[
							                {value:data.successUserCount, name:'正常人数'+data.successUserCount},
							                {value:data.errorUserCount, name:'异常人数'+data.errorUserCount}
							            ]
							        }
							    ]
						    });
					}
				}
			});
		},
		/**
		 * Description: 获取钉钉考勤结果信息  
		 * @author 王荣
		 */
		getClockResult:function(){
			ajaxUtil.ajaxRuquest('dingTalk/getClockResult',
					{'startDay':$("#startDay").val(),
				'endDay':$("#yestarday").val()},
					function(data){
				console.log(data);
			});
		}
}

//时间改变
function dataChange(){
	startDay=$("#startDay").val();
	date=$("#yestarday").val();
	page.getEchart(deptName,date,startDay,searchingWhere,deptId);
	page.getTableData(deptName,date,startDay,searchingWhere,deptId);
}

setInterval ("dataChange()", 900000);//十五分钟更新一次数据
